package com.quanshu.exchange.ui.gui.message.group;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.GroupMemberEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;
import com.quanshu.exchange.ui.gui.message.friends.UserDetailActivity;
import com.quanshu.exchange.ui.gui.message.group.dialog.DialogDeleteGroupMember;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 查看全部群成员->群成员
 * Created by jye on 2018/1/17.
 */

public class AllGroupMemberActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.content_recycler_view)
    RecyclerView contentRecyclerView;

    private SingleAdapter<GroupMemberEntity> adapter;
    private List<GroupMemberEntity> memberEntityList;

    private boolean isShowDelete = false;
    private DialogDeleteGroupMember dialog;

    private GroupEntity groupEntity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_group_members);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initData();
        initListener();
    }

    private void initIntent() {
        memberEntityList = (List<GroupMemberEntity>) getIntent().getSerializableExtra("List<GroupMemberEntity>");
        groupEntity = (GroupEntity) getIntent().getSerializableExtra("GroupEntity");
    }

    private void initView() {

        contentRecyclerView.setLayoutManager(new GridLayoutManager(this, 5));
        adapter = new SingleAdapter<>(new DataDisplayer<GroupMemberEntity>(this, R.layout.item_group_members_avatar) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper<GroupMemberEntity> wrapper, GroupMemberEntity item, int position) {
                holder.setRoundImageUrl(R.id.member_avatar, item.getPhoto(), R.drawable.default_avatar);
                View view = holder.getView(R.id.member_avatar);
                view.setOnLongClickListener(view1 -> {
                    isShowDelete = !isShowDelete;
                    adapter.notifyDataSetChanged();
                    return false;
                });
                if (item.getMemberid().equals(groupEntity.getOwner())) {
                    holder.setVisibility(R.id.group_owner, View.VISIBLE);
                } else {
                    holder.setVisibility(R.id.group_owner, View.GONE);
                }

                if (item.getMemberid().equals(groupEntity.getOwner())) {
                    holder.setVisibility(R.id.group_owner, View.VISIBLE);
                } else {
                    holder.setVisibility(R.id.group_owner, View.GONE);
                }
                holder.setRoundImageUrl(R.id.member_avatar, item.getPhoto(), R.drawable.default_avatar);
                holder.setVisibility(R.id.member_name, View.VISIBLE);

                UserEntity userEntity = UserDao.getInstance().query(item.getMemberid());
                if (userEntity != null) {
                    holder.setVisibility(R.id.member_name, View.VISIBLE);
                    holder.setText(R.id.member_name, AppUtils.getUserName(userEntity));
                } else {
                    holder.setVisibility(R.id.member_name, View.VISIBLE);
                    holder.setText(R.id.member_name, item.getNickname());
                }
                ImageView imageView = holder.getView(R.id.delete_member);
                if (isShowDelete) {
                    imageView.setVisibility(View.VISIBLE);
                } else {
                    imageView.setVisibility(View.GONE);
                }
                RxViewHelper.getInstance().clicks(imageView, aVoid -> doDeleteMember(item));
                if (item.getRelation_type() == 2 || groupEntity.getOwner().equals(currentUser.getMemberid())) {
                    view.setOnClickListener(view1 -> goUserDetailActivity(item));
                }
            }
        });
        contentRecyclerView.setAdapter(adapter);
    }

    private void initListener() {
        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
    }

    private void initData() {
        adapter.setData(memberEntityList);
    }

    private void doDeleteMember(GroupMemberEntity item) {
        // 如果是群主
        if (item.getMemberid().equals(groupEntity.getOwner())) {
            ToastHelper.toast("你的身份是群主，如需退出群聊，请先转移群主");
        } else {
            doShowDialog(item);
        }
    }

    private void doShowDialog(GroupMemberEntity item) {
        if (dialog == null) {
            dialog = new DialogDeleteGroupMember(this);
        }
        dialog.show();
        dialog.getOkSubject().subscribe(o -> doTask(item));
    }

    private void doTask(GroupMemberEntity item) {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .deleteGroupMember(AppUtils.getSignParams(item.getMemberid(), String.valueOf(groupEntity.getGroup_id()), groupEntity.getHx_groupid()), item.getMemberid(),
                        groupEntity.getGroup_id(), groupEntity.getHx_groupid())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }

    private void goUserDetailActivity(GroupMemberEntity memberEntity) {
        if (memberEntity != null) {
            NetClient.getInstance()
                    .getNetService(UserInterface.class)
                    .searchFriend(AppUtils.getSignParams(currentUser.getMemberid(), memberEntity.getMemberid()), currentUser.getMemberid(), memberEntity.getMemberid())
                    .compose(new BaseTransformer<>(this))
                    .subscribe(new BaseObserver<BaseResponse<UserEntity>>() {
                        @Override
                        public void onSuccess(BaseResponse<UserEntity> response) {
                            UserEntity userEntity = response.getInfo();
                            Intent intent = new Intent(AllGroupMemberActivity.this, UserDetailActivity.class);
                            intent.putExtra("UserEntity", userEntity);
                            startActivity(intent);
                        }
                    });
        }
    }
}
